// User Service - 业务逻辑层

const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const userModel = require('./model')
const { jwtSecretKey, expiresIn } = require('@/config/jwt')

/**
 * 用户注册业务逻辑
 */
exports.register = async (username, password) => {
  // 1. 检查用户名是否已存在
  const existingUsers = await userModel.findByUsername(username)
  if (existingUsers.length > 0) {
    throw new Error('用户名被占用，请更换其他用户名！')
  }

  // 2. 加密密码
  const hashedPassword = bcrypt.hashSync(password, 10)

  // 3. 创建用户
  const result = await userModel.create({
    username,
    password: hashedPassword
  })

  if (result.affectedRows !== 1) {
    throw new Error('注册用户失败！')
  }

  return { success: true }
}

/**
 * 用户登录业务逻辑
 */
exports.login = async (username, password) => {
  // 1. 查询用户是否存在
  const users = await userModel.findByUsername(username)
  if (users.length !== 1) {
    throw new Error('用户名不存在！')
  }

  const user = users[0]

  // 2. 验证密码
  const isPasswordValid = bcrypt.compareSync(password, user.password)
  if (!isPasswordValid) {
    throw new Error('密码错误！')
  }

  // 3. 生成 JWT token
  const tokenPayload = { ...user, password: '' }
  const token = jwt.sign(tokenPayload, jwtSecretKey, { expiresIn })

  return {
    token: 'Bearer ' + token,
    user: {
      id: user.id,
      username: user.username
    }
  }
}


/**
 * 根据用户 ID 获取用户信息
 */
exports.getUserInfo = async (id) => {
  const user = await userModel.findById(id)
  if (!user || user.length === 0) {
    throw new Error('用户不存在！')
  }
  return user[0]
}